/*
 * File Name:               XBaseSetting.cs
 * 
 * Description:             普通类
 * Author:                  lisiyu <576603306@qq.com>
 * Create Date:             2017/01/10
 */

using UnityEngine;
using System.IO;

public interface IXBaseLocalSetting
{
    void save();
}

public abstract class XBaseLocalSetting<T> : IXBaseLocalSetting where T : XBaseLocalSetting<T>, new()
{
    private static readonly string RootPathFormat = "LocalSettings/{0}";
    private static readonly string UnityResourcesPath = Application.dataPath + "/Resources/" + RootPathFormat + ".json";

    private static T _singleton;
    public static T Singleton {
        get
        {
            if (_singleton == null)
                _singleton = load();
            return _singleton;
        }
    }

    private static T load()
    {
        var asset = Resources.Load<TextAsset>(string.Format(RootPathFormat, typeof(T).Name));
        if(asset != null)
        {
            return XJsonUtility.FromJson<T>(asset.text);
        }
        else
        {
            return new T();
        }
    }

    public void save()
    {
        File.WriteAllText(string.Format(UnityResourcesPath, typeof(T).Name), XJsonUtility.ToJson_Pretty(this));
#if UNITY_EDITOR && !ENABLE_DEEP_PROFILER
        UnityEditor.AssetDatabase.Refresh();
#endif
    }
}
